import { useLayoutEffect, useRef, useState } from 'react';

import cs from 'classnames';

import styles from './index.module.scss';

export type MarqueeProps = {
  text?: string;
  className?: string | ((overflow: boolean) => undefined | string);
  textClassName?: string;
};

const Marquee: React.FC<MarqueeProps> = ({ text, className, textClassName }) => {
  const $wrap = useRef<HTMLDivElement>(null);
  const $text = useRef<HTMLDivElement>(null);
  const [overflow, setOverflow] = useState(false);

  useLayoutEffect(() => {
    if ($wrap.current && $text.current) {
      const wrapWidth = $wrap.current.clientWidth;
      const textWidth = $text.current.clientWidth;
      setOverflow(textWidth > wrapWidth);
    }
  }, [text]);

  return (
    <div
      className={cs(
        styles['marquee'],
        {
          [styles['overflow']]: overflow
        },
        className instanceof Function ? className(overflow) : className
      )}
      ref={$wrap}
      style={
        {
          '--count': `${(text || '').length / 4}s`
        } as React.CSSProperties
      }
    >
      <div className={cs(styles['text'], textClassName)} ref={$text} data-text={text} />
    </div>
  );
};

export default Marquee;
